<template>
  <view class="person">
    <authorization :isBusiness="is_business">
      <view class="person-header">
        <view style="display: flex">
          <image :src="user.avatar" class="personimg" />
          <view v-if="is_need_phone" class="name">
            <button
              class="loginbtn"
              open-type="getPhoneNumber"
              @getphonenumber="getPhoneNumber"
            >
              授权手机号
            </button>
            <!-- <text @tap="login"></text> -->
          </view>
          <view v-else class="name" style="margin-top: 20rpx">
          <view v-if="is_need_login">
            <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button>
          </view>
          <view v-else>
            <text style="" @tap="login">{{ user.nickName }}
              <!-- <text
                v-show="status == 'yes'"
                style="
                  background: #e95513;
                  border-radius: 8px;
                  font-size: 24rpx;
                  font-weight: 500;
                  color: #ffffff;
                  padding: 12rpx 12rpx 8rpx;
                  margin-left: 10rpx;
                "
              >商户</text> -->
              </text>
            </view>
          </view>
        </view>
        <view
          v-if="is_business == 'no'"
          class="person-header-row"
          style="display: flex"
        >
          <view class="person-header-row-col" @tap="() => onClick('total')"
            ><text>{{ statistics.total }}</text
            ><text>全部</text></view
          >
          <view class="person-header-row-col" @tap="() => onClick('unused')"
            ><text>{{ statistics.unused }}</text
            ><text>未使用卡券</text></view
          >
          <view class="person-header-row-col" @tap="() => onClick('used')"
            ><text>{{ statistics.used }}</text
            ><text>已使用卡券</text></view
          >
          <view class="person-header-row-col" @tap="() => onClick('invalid')"
            ><text>{{ statistics.invalid }}</text
            ><text>失效券</text></view
          >
        </view>
        <view v-else class="person-header-row" style="display: flex">
          <view class="person-header-row-col" style="width: 50%"
            ><text>{{statistics.today}}</text><text>今日核销卡券</text></view
          >
          <view class="person-header-row-col" style="width: 50%"
            ><text>{{statistics.total}}</text><text>一共核销卡券</text></view
          >
        </view>

        <view
          v-if="is_business == null"
          style="
            font-size: 24rpx;
            font-family: PingFangSC;
            font-weight: 300;
            color: #999999;
            margin-top: 100rpx;
            text-align: center;
          "
          >登陆查看消费券信息...</view
        >
        <view v-else-if="is_business == 'no'" style="margin-top: 100rpx">
          <card
            v-for="(item, index) in datalist"
            :key="index"
            :data="item"
          ></card>
        </view>
        <view
          v-else-if="is_business == 'yes'"
          class="business"
          style="margin-top: 100rpx"
        >
          <view class="businessr-row" style="display: flex">
            <view class="business-row-col" @tap="toVerification"
              ><image :src="writeofficon1" /><text>消费券核销</text></view
            >
            <view class="business-row-col" style="margin-left: 20rpx"
              ><image :src="writeofficon2" @tap="toRecord" /><text
                >核销流水</text
              ></view
            >
          </view>

          <view class="writeoff">
            <view class="writeoff-title">今日核销流水</view>
            <writeoff-list :data="todayList"></writeoff-list>
          </view>
        </view>
      </view>
    </authorization>
    <!-- <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
      获取手机号
    </button> -->

    <!-- <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo">
      授权登录
    </button> -->
  </view>
</template>

<script>
import "./index.scss";
import Vue from "vue";
import Taro from "@tarojs/taro";
import { mapState, mapActions, mapMutations } from "vuex";
import img1 from "../../assets/image/build1.png";
import personicon from "../../assets/icon/personicon.png";
import writeoff1 from "../../assets/icon/writeoff1.png";
import writeoff2 from "../../assets/icon/writeoff2.png";
import card from "./components/card/index";
import writeoffList from "./components/writeoffList/index";
import request from "../../utils/request";
import authorization from "../../components/authorization/index";
import {getToken} from '../../utils/token';

export default {
  components: {
    card: card,
    "writeoff-list": writeoffList,
    authorization: authorization,
  },
  data() {
    return {
      is_need_phone: false,
      is_need_login: true,
      personicon: personicon,
      writeofficon1: writeoff1,
      writeofficon2: writeoff1,
      status: "no",
      statistics: {},
      query: {},
      datalist: [],
      todayList:[]
    };
  },

  watch: {
    // 如果 `question` 发生改变，这个函数就会运行
    is_business: function (newQuestion, oldQuestion) {
      if (newQuestion == "no") {
        this.getPersonCouponsList();
      }
    },
  },

  computed: {
    ...mapState({
      user: (state) => {
        return state.user;
      },
      is_business: (state) => {
        // console
        // this.user.phone
        return state.user.is_business;
      },
    }),

  },

  created() {},
  mounted() {
    this.get_user_info();
    // if (this.is_business == "no") {
    //   //this.getStatistics();
    //   this.getConsumerStatistics();
    //   this.getPersonCouponsList();
    // } else {
    //   this.getBusinessStatistics()
    //   // this.getBusinessStatisticsList();
    // }
  },
  methods: {
    ...mapMutations("user", ["setIsBusiness"]),

    init_data()
    {
        console.log("准备调用数据", this.is_business)
    if (this.is_business == "no") {
      //this.getStatistics();
      this.getConsumerStatistics();
      this.getPersonCouponsList();
    } else {
      this.getBusinessStatistics()
      // this.getBusinessStatisticsList();
    }
  },
    get_user_info() 
    {
      request("get", "/api/weixin/get_user_info.htm", {
        openid: getToken(), //"oCh394hHRHVnrvedBv9VxYngNsPs", //openid
      }).then((res) => {
        //this.is_business = res.is_business; 
        this.setIsBusiness(res.is_business);       
        console.log("获取用户个人信息get_user_info", res.is_business, this.is_business);  
        if("" == res.avatarUrl || "undefined" == typeof(res.avatarUrl))
        {
          console.log("需要用户授权登录", res);    
        }else{
          this.is_need_login = false;
          this.user.nickName = res.name;
          this.user.avatar = res.avatarUrl;
        }
        //授权手机号
        if(!this.is_need_login && null == this.is_business)
        {
          this.is_need_phone = true;
        }
        console.log("吼吼吼吼", this.is_business);
        if(null != res.is_business)
        {
          this.init_data();
        }
        //console.log("获取用户个人信息", res);             
      });
    },

    getPhoneNumber(e) {
      var that = this;
      console.log(e, "eeeee");
      console.log(e.detail.errMsg == "getPhoneNumber:ok");
      if (e.detail.errMsg == "getPhoneNumber:ok") {
        request("post", "/api/weixin/get_user_phone.htm", {
          openid: getToken(), //"oCh394hHRHVnrvedBv9VxYngNsPs", //openid
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        }).then((res) => {
          console.log("获取用户手机号", res);
          console.log(res.is_business, "getPhoneNumber");
          this.is_need_phone = false;
          this.setIsBusiness(res.is_business);
          this.get_user_info();
        });
      }
    },
    getBusinessStatisticsList() {
      request("get", "/api/rest/business_statistics.htm").then((res) => {
        console.log(res, "getBusinessStatisticsList");
        // this.statistics = res.statistics;
        //this.todayList = res.today;
      });
    },
    getPersonCouponsList(type) {
      request("get", "/api/rest/consumer_coupons.htm", {
        status: type,
      }).then((res) => {
        console.log(res, "getPersonCouponsList");
        this.datalist = res._list;
        // this.statistics = res.statistics;
      });
    },

    getConsumerStatistics() {
      request("get", "/api/rest/consumer_coupon_statistics.htm").then((res) => {
        console.log(res, "___getStatistics");
        this.statistics = res.statistics;
      });
    },

    getBusinessStatistics() {
      request("get", "/api/rest/business_statistics.htm").then((res) => {
        console.log(res, "___getStatistics");
        this.statistics = res.statistics;
        this.todayList = res.today;
      });
    },

    onClick(type) {
      this.getPersonCouponsList(type);
    },
    login() {
      this.status = this.status + 1;
    },
    toVerification() {
      Taro.navigateTo({ url: "/pages/person/verification/index" });
    },
    toRecord() {
      console.log("333");
      Taro.navigateTo({ url: "/pages/person/record/index" });
    },

    bindGetUserInfo(e) {
      if("getUserInfo:ok" == e.detail.errMsg)
      {
        let res = e.detail;
        let userInfo = res.userInfo;
        let nickName = userInfo.nickName;
        let avatarUrl = userInfo.avatarUrl;
        let gender = userInfo.gender; //性别 0：未知、1：男、2：女
        let province = userInfo.province;
        let city = userInfo.city;
        let country = userInfo.country;
        request("post", "/api/weixin/update_user_info.htm", {
          openid: getToken(),
          nickName: nickName,
          name: nickName,
          avatarUrl: avatarUrl,
        }).then((res)=>{
          this.is_need_login = false;
          this.user.nickName = nickName;
          this.user.avatar = avatarUrl;
          this.get_user_info();          
        });
      }
      
    },
  },
};
</script>
